package com.ricchieri.lazymodel;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.filter.ReservationFilter;
import com.ricchieri.model.Reservation;
import com.ricchieri.service.interf.IReservationService;

public class ReservationLazyDataModel extends LazyDataModel<Reservation> {

	private static final long serialVersionUID = 4593253494642335825L;

	private List<Reservation> reservations;
	private IReservationService reservationService;
	private ReservationFilter reservationFilter;
	
	public ReservationLazyDataModel(IReservationService reservationService, ReservationFilter reservationFilter) {
		super();
		this.reservationFilter = reservationFilter;
		this.reservationService = reservationService;
	}
	
    @Override
    public Object getRowKey(Reservation reservation) {
        return reservation.getId();
    }

    @Override
    public Reservation getRowData(String reservationId) {
        int id = Integer.valueOf(reservationId);

        for (Reservation reservation : reservations) {
            if(id == reservation.getId()) {
                return reservation;
            }
        }
        return null;
    }
    
	@Override
	public List<Reservation> load(int startingAt, int maxPerPage, String sortField, 
			SortOrder sortOrder, Map<String, String> filters) {
		
		if(StringUtils.isNotEmpty(sortField)) {
			reservationFilter.setSortField(sortField);
			reservationFilter.setSortOrder(sortOrder.toString());
		}
		
        if(getRowCount() <= 0) {
            setRowCount(getReservationService().getAllReservationCountByFilter(reservationFilter));
        }
        
        if(getRowCount() == startingAt && getRowCount()  != 0) {
        	startingAt = startingAt - BusinessSettings.ROW_MAX_RESULT;
        }
		reservations = getReservationService().getAllReservationPaginatedByFilter(reservationFilter, startingAt);

        setPageSize(BusinessSettings.ROW_MAX_RESULT);
        
        return reservations;
	}

	public List<Reservation> getReservations() {
		return reservations;
	}

	public void setReservations(List<Reservation> reservations) {
		this.reservations = reservations;
	}

	public IReservationService getReservationService() {
		return reservationService;
	}

	public void setReservationService(IReservationService reservationService) {
		this.reservationService = reservationService;
	}

	public ReservationFilter getReservationFilter() {
		return reservationFilter;
	}

	public void setReservationFilter(ReservationFilter reservationFilter) {
		this.reservationFilter = reservationFilter;
	}
}
